import request from '../utils/request';
import { WorkData, WorkDetailPaginatedResponse, WorkDataRow } from '../types/workDetail';

/**
 * Fetch work detail data by device IDs
 * @param startDate Start date for filtering (YYYY-MM-DD) - optional
 * @param endDate End date for filtering (YYYY-MM-DD) - optional
 * @param deviceIds Optional array of device IDs to filter by
 * @returns Promise with work detail data
 */
export const getWorkDetailByDeviceIds = async (
  startDate?: string,
  endDate?: string,
  deviceIds?: string[]
): Promise<WorkData[]> => {
  const params: any = {};

  if (startDate) {
    params.startDate = startDate;
  }

  if (endDate) {
    params.endDate = endDate;
  }

  if (deviceIds && deviceIds.length > 0) {
    params.deviceIds = deviceIds;
  }

  console.log('Fetching work detail data with params:', params);
  
  try {
    const response: WorkDetailPaginatedResponse = await request.get('/api/admin/web/work-detail/transport-page', { params });
    console.log('API Response:', response);
    
    // Check if response is successful
    if (response.code !== '0000') {
      throw new Error(`API Error: ${response.message}`);
    }
    
    // Transform the API response to match the existing WorkData interface
    const transformedData: WorkData[] = response.data.rows.map((row: WorkDataRow) => ({
      key: row.id.toString(),
      id: row.id.toString(),
      vehicle: row.dtuNumber || '',
      driver: row.username || row.userId || '', // Use username if available, fallback to userId
      startTime: row.startTime,
      endTime: row.endTime,
      startLongitude: row.startLongitude?.toString() || '',
      startLatitude: row.startLatitude?.toString() || '',
      endLongitude: row.endLongitude?.toString() || '',
      endLatitude: row.endLatitude?.toString() || '',
      transportDistance: row.transportDistance?.toString() || '',
      duration: calculateDuration(row.startTime, row.endTime),
      status: determineStatus(row.startTime, row.endTime),
      transportStatus: row.transportStatus // Add transportStatus to the transformed data
    }));
    
    console.log('Transformed data:', transformedData);
    return transformedData;
  } catch (error) {
    console.error('Error fetching work detail data:', error);
    throw error;
  }
};

// Helper function to calculate duration between two timestamps
const calculateDuration = (start: string, end: string): string => {
  try {
    const startTime = new Date(start);
    const endTime = new Date(end);
    const diffMs = endTime.getTime() - startTime.getTime();
    
    // Handle invalid dates
    if (isNaN(diffMs)) {
      return 'Invalid Duration';
    }
    
    const hours = Math.floor(diffMs / (1000 * 60 * 60));
    const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diffMs % (1000 * 60)) / 1000);
    
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  } catch (error) {
    console.error('Error calculating duration:', error);
    return 'Error';
  }
};

// Helper function to determine status based on timestamps
const determineStatus = (start: string, end: string): string => {
  try {
    const startTime = new Date(start);
    const endTime = new Date(end);
    const now = new Date();
    
    // Handle invalid dates
    if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
      return 'unknown';
    }
    
    if (startTime > now) {
      return 'pending'; // Not started yet
    } else if (endTime > now) {
      return 'in-progress'; // In progress
    } else {
      return 'completed'; // Completed
    }
  } catch (error) {
    console.error('Error determining status:', error);
    return 'unknown';
  }
};